# -*- coding: UTF-8 -*-
# @Create   : 2021/11/29 11:01
# @Author   : yh
# @Remark   : 根据视频类型返回对应的获取方式
import logging

from mxsoftpy.exception import ParamsError, DataError

from utils.public.data_process import pwd_db2decode
from index import _

video_model_dict = {
    'HIKVISION': 'hikvision_rtsp'
}


class VideoUrl(object):
    def __check_stream(self, stream_code: str) -> str:
        """
        判断码流是否合法并返回码流值
        :param stream_code: 码流code
        :return: 码流值
        """
        from db.common.VideoManage.VideoQuality.conf import StreamDB

        stream_items = StreamDB('Stream').retrieve(stream_code)

        if stream_items['state'] == 1:
            return stream_items['value']
        else:
            raise DataError('码流无效或不在用，码流code：%s' % stream_code)

    def video_info(self, code: str = None, info: dict = None):
        """
        获取视频信息，如果传入video_info，则使用传入的信息，否则请传入video_code来从数据库获取
        :param code: 要获取的视频code
        :param info: 视频信息
        """
        from db.common.VideoManage.VideoQuality.video import VideoDB

        video_info = info or VideoDB().retrieve(code)
        video_info['stream_code'] = self.__check_stream(video_info['stream_code'])
        return video_info

    def url(self, model, code=None, info=None):
        """
        生成用于视频分析的url
        """
        if not code and not info:
            raise ParamsError(_('生成视频url时，视频code和info都为空'))

        if video_model_dict.get(model):
            return eval('self.' + video_model_dict[model])(self.video_info(code, info))
        else:
            raise ParamsError(_('不支持的视频品牌：%s，现在支持的类型：%s') % (model, str(video_model_dict.keys())))

    def hikvision_rtsp(self, info: dict):
        """
        生成海康威视品牌的rtsp链接
        :param info: 视频信息
        """
        try:
            pwd = pwd_db2decode(info['password'])
        except DataError:
            logging.error('生成海康威视rtsp协议的url时发生错误：该视频的密码无法解码，视频详情%s' % str(info))
            raise DataError(_('生成rtsp错误'))

        return 'rtsp://%s:%s@%s:%s%s/%s0%s' % (
            info['username'], pwd, info['device_ip'], info['port'],
            info['url'], info['aisle'], info['stream_code'])

    def hikvision2_rtsp(self, info: dict):
        """
        生成海康威视品牌的rtsp链接 (第二种方式)
        :param info: 视频信息
        """
        try:
            pwd = pwd_db2decode(info['password'])
        except DataError:
            logging.error('生成海康威视rtsp协议的url时发生错误：该视频的密码无法解码，视频详情%s' % str(info))
            raise DataError(_('生成rtsp错误'))

        return 'rtsp://%s:%s@%s%s' % (info['username'], pwd, info['device_ip'], info['url'])
